<template>
  <div>
    <el-row class="back-head" type="flex" align="middle">
      <span @click="backPath()" style="cursor: pointer"><i class="el-icon-arrow-left"></i>返回</span>
      <span class="primary">创建店铺满减</span>
    </el-row>
    <div class="main">
      <el-form :model="params" ref="ruleForm" label-width="120px" label-position="right" size="small">
        <el-row class="head" type="flex" align="middle">活动信息</el-row>
        <div class="item">
          <el-form-item v-if="$store.state.showAgent" label="所属区域" prop="agentid" :rules="[{ required: true, message: '请选择区域', trigger: 'blur' }]">
            <el-select v-model="params.agentid" filterable default-first-option placeholder="--区域--">
              <el-option v-for="item in restaurants" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="活动名称" prop="name" :rules="[{ required: true, message: '请输入活动名称',trigger: 'blur' }]">
            <el-input v-model="params.name" placeholder="输入活动名称" clearable />
          </el-form-item>
          <el-form-item label="优惠" required>
            <el-row type="flex" v-for="(item,index) in params.runfastFullLess" :key="index">
              <span style="margin-right:5px;">满</span>
              <el-form-item :prop="'runfastFullLess.' + index + '.full'" :rules="[{ required: true, message: '请输入金额' }]">
                <el-input-number :min='item.less?item.less:0' :max='999' :precision='2' v-model="item.full" />
              </el-form-item>
              <span style="margin: 0 5px;">{{comConfig.unit}}减少</span>
              <el-form-item :prop="'runfastFullLess.' + index + '.less'" :rules="[{ required: true, message: '请输入金额'}]">
                <el-input-number v-model="item.less" :min='item.subsidy?item.subsidy:0' :max='item.full?item.full:0' :precision='2' />
              </el-form-item>
              <span style="margin: 0 5px;" >{{comConfig.unit}}，区域承担</span>
              <el-form-item :prop="'runfastFullLess.' + index + '.subsidy'" :rules="[{ required: true, message: '请输入金额'}]">
                <el-input-number :min='0' :max='item.less ? item.less : 0' :precision='2' v-model="item.subsidy" />
              </el-form-item>
              <span style="margin:0 10px;">{{comConfig.unit}}，若有剩余部分由商家承担</span>
              <span>
                <el-button class="el-text-danger" type="text" size="small" @click="deleteThePreferential(index)" v-if="index != 0">
                  <i class="el-icon-remove"></i>移除
                </el-button>
                <el-button class="el-text-success" type="text" @click="newPreferential()" v-if="index === 0 && params.runfastFullLess.length < 5">
                  <i class="el-icon-circle-plus-outline"></i>添加一级满减({{params.runfastFullLess.length}}/5)
                </el-button>
              </span>
            </el-row>
          </el-form-item>
        </div>
        <el-row class="head" type="flex" align="middle">活动时间</el-row>
        <div class="item">
          <el-form-item label="起止日期" prop="startTimeToendTime" :rules="[{ required: true, message: '请起止日期', trigger: 'blur' }]">
            <pt-date-picker style="width: 500px" v-model="params.startTimeToendTime" :disabledDate=" time => time.getTime() <= (Date.now() - 3600 * 1000 * 24)" />
          </el-form-item>
          <el-form-item label="生效星期" prop="worktoday" :rules="[{ type:'array', required: true, message: '最少选择一天工作日', trigger: 'change'},]">
            <el-checkbox-group v-model="params.worktoday">
              <el-checkbox style="margin-left: 0;margin-right: 30px;" v-for="(week,index) in weeks" :label="index+1" :key="index">{{week}}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="生效时间段" required>
            <el-radio v-model="timeType" :label="1">全天</el-radio>
            <el-radio v-model="timeType" :label="2">自定义时间</el-radio>
          </el-form-item>
          <el-form-item label="自定义时间" required v-if="timeType === 2" style="margin-bottom: 0">
            <el-row>(最少选择一个)</el-row>
            <el-row type="flex"> 自定义时间一：
              <el-form-item prop="firstTime" :rules="[{type:'date',validator:firstTime, trigger: 'change' }]">
                <el-time-picker is-range v-model="params.firstTime" range-separator="至" start-placeholder="开始时间"
                  end-placeholder="结束时间" placeholder="选择时间范围" format="HH:mm" value-format="HH:mm" />
              </el-form-item>
            </el-row>
            <el-row type="flex"> 自定义时间二：
              <el-form-item prop="secondTime" :rules="[{type:'date',validator:secondTime, trigger: 'change' }]">
                <el-time-picker is-range v-model="params.secondTime" range-separator="至" start-placeholder="开始时间"
                  end-placeholder="结束时间" placeholder="选择时间范围" format="HH:mm" value-format="HH:mm" />
              </el-form-item>
            </el-row>
            <el-row type="flex"> 自定义时间三：
              <el-form-item prop="thirdTime" :rules="[{type:'date',validator:thirdTime, trigger: 'change' }]">
                <el-time-picker is-range v-model="params.thirdTime" range-separator="至" start-placeholder="开始时间"
                  end-placeholder="结束时间" placeholder="选择时间范围" format="HH:mm" value-format="HH:mm" />
              </el-form-item>
            </el-row>
          </el-form-item>
        </div>
        <el-row class="head" type="flex" align="middle">同享设置</el-row>
        <div class="item">
          <el-form-item label="是否同享" required>
            <el-switch v-model="params.shared" size="small" />
          </el-form-item>
        </div>
        <el-row>
          <el-form-item>
            <el-button @click="submitForm('ruleForm')" :loading="issubmitLoading"
              style="color:#fff;background: rgb(246, 82, 47);">保存去选门店
            </el-button>
          </el-form-item>
        </el-row>
      </el-form>
    </div>

  </div>
</template>
<script>
  export default {
    data() {
      return {
        timeType: 1, // 自定义或者全天
        weeks: [ '周一', '周二', '周三', '周四', '周五', '周六','周日',],
        issubmitLoading: false, // 提交表单等待
        params: {
          agentid: '', // 区域id
          ptype: '1', //活动类型 1满减
          name: '',  //活动名称
          runfastFullLess: [{ id: '', fulls: '', lesss: '', subsidy: '' }], // 优惠
          startTimeToendTime: '', //活动起止时间
          worktoday: [1, 2, 3, 4, 5, 6, 7], //星期
          firstTime: '', //时间一
          secondTime: '', //时间二
          thirdTime: '', //时间三
          shared: false, //同享
        },
      }
    },
    computed: {
      restaurants() { // 区域数据
        return this.$store.state.agentList
      }
    },
    watch: {
      restaurants: {
        handler(val) {
          if (val && val.length) {
            if (val.length === 1) { // 只有一个区域 直接显示
              this.params.agentid = val[0].id
            }
          }
        },
        deep: true
      }
    },
    methods: {
      firstTime(rule, value, callback) { //时间验证
        if (this.timeType === 2 && !value) {
          callback(new Error('选择自定义时间，自定义时间一必填!'))
        } else {
          callback()
        }
      },
      secondTime(rule, value, callback) { // 时间验证
        if (this.params.firstTime && value && value[0] <= this.params.firstTime[1]) {
          callback(new Error('自定义时间二的开始时间需大于自定义时间一的结束时间'))
        } else {
          callback()
        }
      }, thirdTime(rule, value, callback) { // 时间验证
        if (this.params.secondTime && value && value[0] <= this.params.secondTime[1]) {
          callback(new Error('自定义时间三的开始时间需大于自定义时间二的结束时间'))
        } else {
          callback()
        }
      },
      newPreferential() { // 添加满减少优惠
        this.params.runfastFullLess.push({id: '', full: '', less: '', subsidy: ''})
      },
      deleteThePreferential(index) { // 删除规格
        this.params.runfastFullLess.splice(index, 1)
      },
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            const params = { ...this.params }
            if (this.timeType === 1) {
              params.firstTime = ''
              params.secondTime = ''
              params.thirdTime = ''
            }
            params.firstTime = params.firstTime ? params.firstTime.join(',') : ''
            params.secondTime = params.secondTime ? params.secondTime.join(',') : ''
            params.thirdTime = params.thirdTime ? params.thirdTime.join(',') : ''
            params.startTimeToendTime = params.startTimeToendTime ? params.startTimeToendTime.join(',') : ''
            this.issubmitLoading = true
            this.$http.post('/server/activity/save', JSON.stringify(params)).then(res => {
              if (res.data.success) {
                this.$message({type: 'success', message: '新增满减活动成功'})
                this.$router.push({path: '/main/activity/cfullless', query: {id: res.data.data.activityId}})
              }
            }).finally(() => { this.issubmitLoading = false })
          } else {
            this.$message.error('有不合法的输入或未填写的输入，请检查页面')
            return false
          }
        })
      },
      backPath() {
        this.$router.replace({path: '/main/activity/pron'})
      }
    },
    mounted() {
      if (this.restaurants && this.restaurants.length === 1) {
        this.params.agentid = this.restaurants[0].id
      }
    }
  }
</script>
<style lang="scss" scoped>
  .primary {
    color: $c-active-full;
  }
  .main .head {
    background: $c-active-full;
  }
  @import './css/actives.scss';
</style>
